package com.lianwei.hospital.controller;

import com.lianwei.hospital.Service.AdmainService;
import com.lianwei.hospital.module.entity.Admain;
import com.lianwei.hospital.utils.JwtUtils;
import com.lianwei.hospital.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
@RequestMapping("/admain")
public class AdmainController {
    @Autowired
    private AdmainService admainService;

    @PostMapping("/login")
    public Result<Admain> login(@RequestParam("username") String name, @RequestParam("password") String password, HttpSession session) throws Exception{
        Admain admain= admainService.login(name, password);
        System.out.println("asd\n\n");
        if (admain!=null){
            session.setAttribute("admain",admain);
            String res= JwtUtils.sign(name, String.valueOf(admain.getAId()));
            System.out.println(res);
            return Result.buildResult(Result.Status.OK,res);
        }
        return Result.buildResult(Result.Status.BAD_REQUEST);
    }

    @GetMapping("/selectById")
    public Result<Admain> Select(Integer i) throws Exception {
        System.out.println(i+"\n\n");
        Admain admain = admainService.selectByPrimaryKey(i);
        return Result.buildResult(Result.Status.OK,admain);
    }

    @PutMapping
    public Result<List<Admain>> Insert(@RequestBody Admain admain) throws Exception {
        System.out.println(admain);
        if(admainService.insert(admain)){
            List<Admain> admainList = admainService.selectAll();
            return Result.buildResult(Result.Status.OK,admainList);
        }
        return Result.buildResult(Result.Status.BAD_REQUEST);
    }

    @DeleteMapping
    public Result<List<Admain>> Delete(@RequestBody Admain admain) throws Exception {
        System.out.println(admain);
        if(admainService.deleteByPrimaryKey(admain.getAId())){
            List<Admain> admainList = admainService.selectAll();
            return Result.buildResult(Result.Status.OK,admainList);
        }
        return Result.buildResult(Result.Status.BAD_REQUEST);
    }

    @PostMapping
    public Result<List<Admain>> Update(@RequestBody Admain admain) throws Exception {
        System.out.println(admain);
        if(admainService.updateByPrimaryKey(admain)){
            List<Admain> admainList = admainService.selectAll();
            return Result.buildResult(Result.Status.OK,admainList);
        }
        return Result.buildResult(Result.Status.BAD_REQUEST);
    }

    @GetMapping("/selectAll")
    public Result<List<Admain>> abc() throws Exception {
        List<Admain> admainList = admainService.selectAll();
        System.out.println(admainList);
        return Result.buildResult(Result.Status.OK,admainList);
    }


}
